
package com.vanda.db;
import com.vanda.db.cfg.Environment;
import com.vanda.db.cfg.MappingInfo;
import com.vanda.db.exception.DbException;

/**
 * 根据XML定义的内容操作数据库<br>
 * 
 * @author 王瑛<br>
 * @version Version 1.00<br>
 */
public class XMLAccessor {
	/**
	 * xql类型，[sql,hql]
	 */
	private String type = null;
	/**
	 * 是否查询语句,hql没有非查询语句
	 */
	private boolean query = false;
	/**
	 * 运行xml配置文件的xql
	 * 相当于调用operate(name,dataBean,false);
	 * @param name xql名字
	 * @param dataBean 查询参数，如果有多个，用Object[]传递，而不要用Collection接口类
	 * @return 如果是hql,则返回BeanListBase型，如果是sql且是查询，返回List型
	 * 如果是sql且是非查询，则返回int[]型
	 * @throws DbException
	 */
	public Object operate(String name, Object dataBean) throws DbException {
		return operate(name, dataBean, false);
	}
	/**
	 * 运行xml配置文件的xql
	 * 相当于调用operate(name,dataBean,false);
	 * @param name xql名字
	 * @param dataBean 参数
	 * @param bTransaction 是否进行事务处理，true-进行,false-不进行
	 * @return 如果是查询,则返回BeanListBase型
	 * 如果是sql且是非查询，则返回int[]型
	 * @throws DbException
	 */
	public Object operate(String name, Object dataBean, boolean bTransation)
		throws DbException {
		Object result = null;
		Accessor accessor = null;
		try {
			MappingInfo info = Accessor.findMapping(name);
			this.type = info.getType();
			this.query = info.isQuery();
			int accessorType = getAccessorType();
			accessor =
				DBFactory.getAccessor(info.getConnection(), accessorType);
			if (bTransation)
				accessor.begin();
			if (query) {
				result = accessor.queryName(name, dataBean);
			} else {
				if (accessor instanceof HQLAccessor) {
					throw new DbException("HQL cannot be non-query !");
				}
				result = ((SQLAccessor) accessor).executeName(name, dataBean);
			}
			if (bTransation)
				accessor.commit();
		} catch (DbException e) {
			if (bTransation) {
				accessor.rollback();
			}
			throw e;
		} catch (Exception e) {
			if (bTransation) {
				accessor.rollback();
			}
			throw new DbException("Operator Error!", e);
		} finally {
			if (accessor != null) {
				accessor.close();
			}
		}
		return result;
	}
	
	/** 
	 * 取得Accessor类型
	 * @return
	 */
	private int getAccessorType() {
		int accessorType = DBFactory.ACCESSOR_TYPE_HQL;
		if (type.equals(Environment.TYPE_SQL)) {
			accessorType = DBFactory.ACCESSOR_TYPE_SQL;
		}
		return accessorType;
	}
	public boolean isQuery() {
		return query;
	}

	public String getType() {
		return type;
	}
}
